package kz.edu.sdu.atm.server;

import java.io.PrintWriter;
import java.util.Scanner;
import java.util.regex.Pattern;

import kz.edu.sdu.atm.models.OperationType;
import kz.edu.sdu.atm.models.Request;
import kz.edu.sdu.atm.models.Response;
import kz.edu.sdu.atm.util.Logger;

public class ComProtocol extends IComProtocol {
	Logger log = new Logger(ComProtocol.class);
	public static Pattern REQUEST_PATTERN = Pattern
			.compile("~[a-zA-Z]+:[a-zA-Z]+:[a-zA-Z]+:[a-zA-Z0-9=;.]*~");
	public static String RESPONSE_FORMAT = "~%s:%s~";

	public ComProtocol(Scanner in, PrintWriter out, IServer s) {
		this.in = in;
		this.out = out;
		this.server = s;
	}

	@Override
	public Request readRequest(Scanner in) {
		String line = in.findInLine(REQUEST_PATTERN);
		Request result = null;
		if (line != null) {
			line = line.substring(1, line.length() - 1);
			log.debug("request: " + line);
			String[] r = line.split(":");
			if (r.length != 4){
				log.warn("size of request line is suspicious: " + r.length);
			}
			result = new Request();
			result.setUsername(r[0]);
			result.setPassword(r[1]);
			result.setOperation(OperationType.valueOf(r[2]));
			if (r.length > 3 && r[3] != null && r[3].length() > 0) {
				String[] mr = r[3].split(";");
				int k = mr.length;
				for (int i = 0; i < k; i++){
					String[] kv = mr[i].split("=");
					result.getMap().put(kv[0], kv[1]);
				}
			}
			log.debug("request-taken: " + result.toString());
		}
		return result;
	}

	@Override
	public void writeResponse(PrintWriter out, Response res) {
		String result = String.format(RESPONSE_FORMAT, res.getStatus()
				.toString(),
				res.getMessage());
		out.println(result);
		out.flush();
		log.debug("reply: " + result);
	}

}
